package com.enthal.basicpers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.util.Log
import android.widget.Toast

class MsgReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Log.i(">> BroadCast",intent.action)

        when (intent.action) {
            // 系统启动开启服务.
            Intent.ACTION_BOOT_COMPLETED -> {
                val mIntent = Intent(context, NoticeListenerService::class.java)
                context.startService(mIntent)
            }

            Intent.ACTION_BATTERY_LOW -> {
                Log.w("PhoneStatus", "手机状态警告: 端开连接.")
                RuntimeStatus.sendTestNotice(context, "网络状态变更","连接端开")
            }

            // 网络连接状态变化 CONNECTIVITY_CHANGE
            ConnectivityManager.CONNECTIVITY_ACTION -> {
                val isconn = RuntimeStatus.iNetConnected(context)
                if(!isconn) {
                    Log.e("PhoneStatus", "手机状态警告: 网络断开连接.")
                    RuntimeStatus.sendTestNotice(context, "手机状态警告","网络断开连接")
                    val wifiManager =
                        context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                    wifiManager.isWifiEnabled = true
                }
                else
                    Log.i("PhoneStatus", "手机状态警告: 网络重新连接.")
            }

             WifiManager.WIFI_STATE_CHANGED_ACTION -> {
                val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                WifiManager.WIFI_STATE_DISABLED);
                 when(wifiState) {
                     WifiManager.WIFI_STATE_DISABLED ->
                         Toast.makeText(context, "wifi distabled", Toast.LENGTH_SHORT).show()
                     WifiManager.WIFI_STATE_ENABLED->
                         Toast.makeText(context, "wifi enabled", Toast.LENGTH_SHORT).show()
                 }
            }
            WifiManager.NETWORK_STATE_CHANGED_ACTION ->
                Toast.makeText(context, "net stat changed", Toast.LENGTH_SHORT).show()

            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION ->
                Toast.makeText(context, "scanned available", Toast.LENGTH_SHORT).show()

            else-> Toast.makeText(context, "BroadCast "+intent.action, Toast.LENGTH_LONG).show()
        }
    }
}
